package com.charmpeach.tsss.forum;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.charmpeach.tsss.customer.LogInterface;
import com.charmpeach.tsss.customer.LogManager;

public class Forum implements ForumInterface {
	String sessionID = null;
	DefaultHttpClient client = null;
	
	public Forum (){
		LogInterface li = new LogManager();
		
		sessionID = li.login();		
		if(sessionID == null)
			return;
		
		client = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://218.94.159.102/tss/en/home/postSignin.html?SIGlobalLogin=" + sessionID);
		try
		{
			client.execute(get);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean reply(String threadId, String content, String courseId) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("threadId", threadId));
		nameValuePairs.add(new BasicNameValuePair("content", content));
		
		String url = "http://218.94.159.102/tss/en/" + courseId + "/forum/postReply/"; 
		HttpPost post = new HttpPost(url);
		
		try
		{
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			client.execute(post);
			return true;
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
	}

	@Override
	public boolean newTopic(String title, String content, String courseId) {
		// TODO Auto-generated method stub
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("title", title));
		nameValuePairs.add(new BasicNameValuePair("content", content));
		
		String url = "http://218.94.159.102/tss/en/" + courseId + "/forum/postTopic/"; 
		HttpPost post = new HttpPost(url);
		
		try
		{
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			client.execute(post);
			return true;
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
	}

}
